﻿<template>
    <div class="InBillDetail">
        <MyDialog :model-value="true" :type="DialogType.C3" :title="title" @close="onClose">
            <el-form ref="InBillDetailFormRef" label-width="80" :model="thisData" :rules="rules" :disabled="isSee">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="入库单号" prop="code">
                            <el-input v-model="thisData.code" maxlength="50"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库仓库" prop="warehouseID">
                            <DataSelect class="w-100" table="Warehouse" v-model:id="thisData.warehouseID" v-model:name="thisData.warehouseName"></DataSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库类型" prop="operTypeID">
                            <DataSelect class="w-100" table="OperType" :filter="{ _InOutType: Enums.OperType_InOutType.入库 }" v-model:id="thisData.operTypeID" v-model:name="thisData.operTypeName"></DataSelect>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="申请人" prop="applyUserName">
                            <el-input v-model="thisData.applyUserName" disabled maxlength="50"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="申请日期" prop="billDate">
                            <el-date-picker class="w-100" v-model="thisData.billDate" type="date" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"> </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="入库备注" prop="remark">
                            <el-input v-model="thisData.remark" maxlength="500"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="rowWarp">
                <div class="rowTitle marb-10 mart-10" v-if="true">入库明细</div>
                <div class="btnBox" v-if="!isSee && !isCheck">
                    <el-button type="primary" @click="onAddRow">添加</el-button>
                    <!-- <el-button type="warning" @click="onDownTest">模板下载</el-button>
                    <el-upload class="marl-10 marr-10" :auto-upload="false" accept=".xlsx" :limit="1" :show-file-list="false" :on-change="onImportFileChange">
                        <el-button type="warning">导入</el-button>
                    </el-upload> -->
                    <el-button type="danger" @click="onDelete">删除</el-button>
                </div>
            </div>
            <DataTable ref="InBillDetailTableRef" divHeight="360px" :data="thisData.billDetailModels" :border="false" :hasCheckbox="!isSee" :hasTop="false" :hasPager="false" :requiredArr="['钢丝绳名称', '规格型号', '直径', '长度', '绳子条数']">
                <vxe-column title="钢丝绳编码" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <el-input v-model="row.code" maxlength="50" disabled></el-input>
                    </template>
                </vxe-column>

                <vxe-column title="钢丝绳名称" min-width="200" show-overflow>
                    <template #default="{ row }">
                        <el-input v-model="row.name" maxlength="50" :disabled="isSee"></el-input>
                    </template>
                </vxe-column>

                <vxe-column title="规格型号" min-width="200" show-overflow>
                    <template #default="{ row, rowIndex }">
                        <el-input v-model="row.guiGe" maxlength="200" disabled>
                            <template #append v-if="!isSee">
                                <el-button @click="onOpenWireropeSelect(rowIndex)">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </template>
                </vxe-column>

                <vxe-column title="直径" min-width="150" show-overflow>
                    <template #default="{ row }">
                        <InputNumber v-model="row.diameter" :disabled="isSee" append="mm"></InputNumber>
                    </template>
                </vxe-column>

                <vxe-column title="公称捻距" min-width="150" show-overflow>
                    <template #default="{ row }">
                        <InputNumber v-model="row.nianJu" :disabled="isSee" append="mm"> </InputNumber>
                    </template>
                </vxe-column>

                <vxe-column title="抗拉强度" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <DataSelect table="Mpa" class="w-100" v-model:id="row.mpaID" v-model:name="row.mpaName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="表面状态" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <DataSelect table="SurfaceStatus" class="w-100" v-model:id="row.surfaceStatusID" v-model:name="row.surfaceStatusName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="捻制类型" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <DataSelect table="TwistingType" class="w-100" v-model:id="row.twistingTypeID" v-model:name="row.twistingTypeName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="长度" min-width="150" show-overflow>
                    <template #default="{ row }">
                        <InputNumber v-model="row.lengthNum" :disabled="isSee" append="m"></InputNumber>
                    </template>
                </vxe-column>

                <vxe-column title="绳子条数" min-width="150" show-overflow>
                    <template #default="{ row }">
                        <InputNumber v-model="row.cnt" :precision="0" :disabled="isSee" append="根"> </InputNumber>
                    </template>
                </vxe-column>

                <vxe-column title="维保周期" min-width="150" show-overflow>
                    <template #default="{ row }">
                        <InputNumber v-model="row.keepDay" :precision="0" :disabled="isSee" append="天"> </InputNumber>
                    </template>
                </vxe-column>

                <vxe-column title="供应商" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <DataSelect table="Supplier" class="w-100" v-model:id="row.supplierID" v-model:name="row.supplierName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="制造商" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <DataSelect table="Producer" class="w-100" v-model:id="row.producerID" v-model:name="row.producerName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="出厂报告" min-width="100" show-overflow>
                    <template #default="{ row }">
                        <ButtonImage v-model="row.chuChang_FilesList" appendToBody :readonly="isSee" type="warning" :text="isSee ? '查看' : '上传'"></ButtonImage>
                    </template>
                </vxe-column>

                <vxe-column title="验收报告" min-width="100" show-overflow>
                    <template #default="{ row }">
                        <ButtonImage v-model="row.yanShou_FilesList" appendToBody :readonly="isSee" type="warning" :text="isSee ? '查看' : '上传'"></ButtonImage>
                    </template>
                </vxe-column>

                <vxe-column title="倒卷检测报告" min-width="100" show-overflow>
                    <template #default="{ row }">
                        <ButtonImage v-model="row.jianCe_FilesList" appendToBody :readonly="isSee" type="warning" :text="isSee ? '查看' : '上传'"></ButtonImage>
                    </template>
                </vxe-column>

                <vxe-column title="附件" min-width="100" show-overflow>
                    <template #default="{ row }">
                        <ButtonImage v-model="row.attr_FilesList" appendToBody :readonly="isSee" type="warning" :text="isSee ? '查看' : '上传'"></ButtonImage>
                    </template>
                </vxe-column>

                <vxe-column title="矿山" min-width="120" show-overflow>
                    <template #default="{ row }">
                        <DataSelect table="Department" class="w-100" :filter="{ _Type: Enums.Department_Type.矿山 }" v-model:id="row.departmentID" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="提升机类型" min-width="120" show-overflow>
                    <template #default="{ row, rowIndex }">
                        <DataSelect table="Hoister" class="w-100" v-model:id="row.hoisterID" v-model:name="row.hoisterName" :disabled="isSee" @change="onHoisterChange(rowIndex, row.hoisterID)"></DataSelect>
                        <!-- <DataSelect :ref="(el) => (HoisterRefs[rowIndex] = el)" table="Hoister" class="w-100" v-model:id="row.hoisterID" v-model:name="row.hoisterName" :disabled="isSee" @change="onHoisterChange(rowIndex)"></DataSelect> -->
                    </template>
                </vxe-column>

                <vxe-column title="提升用途" min-width="120" show-overflow>
                    <template #default="{ row, rowIndex }">
                        <!-- <DataSelect table="HoisterUsage" class="w-100" :filter="{ _HoisterID: row.hoisterID }" v-model:id="row.hoisterUsageID" v-model:name="row.hoisterUsageName" :disabled="isSee"></DataSelect> -->
                        <DataSelect :ref="(el) => (HoisterUsageRefs[rowIndex] = el)" class="w-100" :isLoadingData="false" v-model:id="row.hoisterUsageID" v-model:name="row.hoisterUsageName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="钢丝绳类型" min-width="120" show-overflow>
                    <template #default="{ row, rowIndex }">
                        <!-- <DataSelect table="WireropeType" class="w-100" :filter="{ _HoisterID: row.hoisterID }" v-model:id="row.wireropeTypeID" v-model:name="row.wireropeTypeName" :disabled="isSee"></DataSelect> -->
                        <DataSelect :ref="(el) => (WireropeTypeRefs[rowIndex] = el)" class="w-100" :isLoadingData="false" v-model:id="row.wireropeTypeID" v-model:name="row.wireropeTypeName" :disabled="isSee"></DataSelect>
                    </template>
                </vxe-column>

                <vxe-column title="备注" min-width="200" show-overflow>
                    <template #default="{ row }">
                        <el-input v-model="row.remark" :disabled="isSee"></el-input>
                    </template>
                </vxe-column>

                <vxe-column title="分配库位" min-width="120" show-overflow v-if="isCheck || thisData.status == Enums.Bill_Status.已验收" :fixed="thisData.status == Enums.Bill_Status.验收中 ? 'right' : ''">
                    <template #default="{ row }">
                        <DataSelect table="WarehousePosition" class="w-100" :filter="{ _WarehouseID: thisData.warehouseID }" :disabled="isSee && !isCheck" v-model:id="row.warehousePositionID" v-model:name="row.warehousePositionName"></DataSelect>
                    </template>
                </vxe-column>
            </DataTable>

            <WireropeSelect v-if="isShowWireropeSelect" :hasCheckbox="false" :hasRadio="true" @close="onCloseWireropeSelect" :defaultFilter="wireropeFilter"></WireropeSelect>

            <template #footer>
                <el-button type="danger" :loading="loading" @click="onBack" v-if="isCheck">退回</el-button>
                <el-button type="primary" :loading="loading" @click="onSubmit('提交')" v-if="!isSee || isCheck">提交</el-button>
                <el-button type="warning" :loading="loading" @click="onSubmit('保存')" v-if="!isSee">保存</el-button>
            </template>
        </MyDialog>
    </div>
</template>

<script lang="ts" setup>
import Enums from "@/gx/Enums";
import Gx from "@/gx/Gx";
import { FormRules } from "element-plus";
import { DialogType, TipsType } from "@/_gx/TsEnums";
import { tokenStore } from "@/stores/tokenStore";
import WireropeSelect from "@/views/base/Wirerope/WireropeSelect.vue";
import _ from "lodash";
import LAY_EXCEL from "lay-excel";

const store = tokenStore();
//接收父组件的传值
const rowAutoID = inject("rowAutoID") as Ref<number | null>;

//定义当前页面数据对象
const thisData = ref<any>({});

//loading...
const loading = ref(false);

//查看
const isSee = ref(false);
const isCheck = ref(false);

//定义表单验证规则
const rules = ref<FormRules>({
    operTypeID: [{ required: true, message: "请选择入库类型", trigger: "change" }],
    warehouseID: [{ required: true, message: "请选择入库仓库", trigger: "change" }],
    applyUserName: [{ required: true, message: "请输入申请人", trigger: "blur" }],
});

//标题
const title = computed(() => {
    if (Gx.IsEmpty(rowAutoID.value)) {
        return "单据详情 - 创建";
    } else {
        return `单据详情 - 编辑 - ${thisData.value.code}`;
    }
});

//默认入库明细
let defaultBillDetailData = {
    code: "",
    name: "",
    guiGe: "",
    diameter: null,
    nianJu: null,
    mpaID: null,
    mpaName: "",
    surfaceStatusID: null,
    surfaceStatusName: "",
    twistingTypeID: null,
    twistingTypeName: "",
    lengthNum: null,
    cnt: null,
    keepDay: null,
    supplierID: null,
    supplierName: "",
    producerID: null,
    producerName: "",
    chuChang_FilesList: [],
    yanShou_FilesList: [],
    jianCe_FilesList: [],
    attr_FilesList: [],
    departmentID: null,
    hoisterID: null,
    hoisterName: "",
    hoisterUsageID: null,
    hoisterUsageName: "",
    wireropeTypeID: null,
    wireropeTypeName: "",
    remark: "",
};

// 提升用途 钢丝绳类型
const HoisterUsageRefs = ref([]);
const WireropeTypeRefs = ref([]);
const hoisterUsageList = ref([]);
const wireropeTypeList = ref([]);
//初始化
const Init = async (type) => {
    if (type) {
        isSee.value = true;
        if (type == 2) {
            isCheck.value = true;
        }
    }
    await App.CallApi(Api.HoisterUsage.GetSearchWithIsDelete(), {
        success: (res) => {
            hoisterUsageList.value = res;
        },
    });
    await App.CallApi(Api.WireropeType.GetSearchWithIsDelete(), {
        success: (res) => {
            wireropeTypeList.value = res;
        },
    });

    if (!Gx.IsEmpty(rowAutoID.value)) {
        App.CallApi(Api.Bill.GetByID(rowAutoID.value), {
            success: (res) => {
                if (!Gx.IsEmpty(res.backReason) && res.status == Enums.Bill_Status.创建中) {
                    App.Alert({
                        type: TipsType.Error,
                        title: "提示",
                        okText: "我知道了",
                        dangerouslyUseHTMLString: true,
                        msg: "单据信息被打回，请修改后重新提交<br/>打回原因：<span class='color-error'>" + res.backReason + "</span>",
                    });
                }
                thisData.value = res;

                for (let i = 0; i < res.billDetailModels.length; i++) {
                    let item = res.billDetailModels[i];
                    item.uid = Gx.GenerateUUID();
                    nextTick(() => {
                        if (item.hoisterID) {
                            HoisterUsageRefs.value[i].SetList(hoisterUsageList.value.filter((it) => it.hoisterID == item.hoisterID));
                            WireropeTypeRefs.value[i].SetList(wireropeTypeList.value.filter((it) => it.hoisterID == item.hoisterID));
                        } else {
                            HoisterUsageRefs.value[i].SetList([]);
                            WireropeTypeRefs.value[i].SetList([]);
                        }
                    });
                }
            },
        });
    } else {
        thisData.value.inOutType = Enums.OperType_InOutType.入库;
        thisData.value.applyUserID = store.me.userID;
        thisData.value.applyUserName = store.me.name;
        thisData.value.billDate = Gx.FormatDate("YYYY-MM-DD");
        thisData.value.billDetailModels = [];
        let item = Gx.DeepCopy(defaultBillDetailData);
        item.uid = Gx.GenerateUUID();
        thisData.value.billDetailModels.push(item);
    }
};

//表单Ref对象
const InBillDetailFormRef = ref();
const InBillDetailTableRef = ref();

//添加
const onAddRow = () => {
    let item = Gx.DeepCopy(defaultBillDetailData);
    item.uid = Gx.GenerateUUID();
    thisData.value.billDetailModels.push(item);
};

//模板下载
const onDownTest = () => {};

//导入文件
const onImportFileChange = (file: any) => {
    LAY_EXCEL.importExcel(
        [file.raw],
        {
            fields: {
                id: "A",
                username: "B",
                experience: "C",
                sex: "D",
                score: "E",
                city: "F",
                classify: "G",
                wealth: "H",
                sign: "I",
            },
        },
        (data) => {
            console.log(data);
        }
    );
};

//删除
const onDelete = () => {
    let selectIndexs: [] = InBillDetailTableRef.value.GetSelectIndex("uid");
    if (Gx.IsEmpty(selectIndexs) || selectIndexs.length == 0) {
        App.Tips({ msg: "请在下方的表格中选择相应的数据！" });
        return;
    }
    let delArr = _.orderBy(selectIndexs, null, "desc");

    App.Confirm({
        msg: "确定要删除选择的数据？",
        type: TipsType.Warning,
        onOk: () => {
            delArr.forEach((x) => {
                thisData.value.billDetailModels.splice(x, 1);
            });
        },
    });
};

//提交 保存
const onSubmit = (type) => {
    InBillDetailFormRef.value.validate((isOk: boolean) => {
        if (!isOk) {
            return;
        }

        if (!thisData.value.billDetailModels || !thisData.value.billDetailModels.length) {
            App.Tips({ msg: "请添加入库明细！" });
            return;
        }

        for (let i = 0; i < thisData.value.billDetailModels.length; i++) {
            const element = thisData.value.billDetailModels[i];
            element.warehouseID = thisData.value.warehouseID;
            element.warehouseName = thisData.value.warehouseName;
            if (Gx.IsEmpty(element.name)) {
                App.Tips({ msg: "请填写序号【 " + (i + 1) + " 】的钢丝绳名称！" });
                return;
            }
            if (Gx.IsEmpty(element.guiGe)) {
                App.Tips({ msg: "请填写" + (i + 1) + "的规格型号！" });
                return;
            }
            if (Gx.IsEmpty(element.diameter)) {
                App.Tips({ msg: "请填写" + (i + 1) + "的直径！" });
                return;
            }
            if (Gx.IsEmpty(element.lengthNum)) {
                App.Tips({ msg: "请填写" + (i + 1) + "的长度！" });
                return;
            }
            if (Gx.IsEmpty(element.cnt)) {
                App.Tips({ msg: "请填写" + (i + 1) + "的绳子条数！" });
                return;
            }
            if (Gx.IsEmpty(element.warehousePositionID) && isCheck.value) {
                App.Tips({ msg: "请选择" + (i + 1) + "的库位！" });
                return;
            }
        }

        let _api = null;
        let _data = thisData.value;
        if (type == "提交") {
            if (isCheck.value) {
                //验收
                _api = Api.Bill.ConfirmForIn;
            } else {
                _api = Api.Bill.SubmitForIn;
            }
        } else {
            if (Gx.IsEmpty(rowAutoID.value)) {
                //添加
                _api = Api.Bill.Insert;
            } else {
                //修改
                _api = Api.Bill.Update;
            }
        }

        loading.value = true;
        App.CallApi(_api, {
            data: _data,
            success: (res) => {
                App.Tips({ type: TipsType.Success, msg: "操作成功！" });
                emits("close", true);
            },
            complete: () => {
                loading.value = false;
            },
        });
    });
};

// 退回
const onBack = () => {
    App.Prompt({
        msg: "请输入退回原因",
        title: "退回",
        type: null,
        inputPattern: /^\S{1,100}$/,
        inputErrorMessage: "请输入退回原因，内容不超过100个字符！",
        onOk: (value) => {
            loading.value = true;
            thisData.value.backReason = value;
            App.CallApi(Api.Bill.BackForIn, {
                data: thisData.value,
                success: (res) => {
                    App.Tips({ type: TipsType.Success, msg: "操作成功！" });
                    emits("close", true);
                },
                complete: () => {
                    loading.value = false;
                },
            });
        },
    });
};

//改变提升机类型
const onHoisterChange = (idx, hoisterID) => {
    HoisterUsageRefs.value[idx].ClearData();
    WireropeTypeRefs.value[idx].ClearData();
    nextTick(() => {
        HoisterUsageRefs.value[idx].SetList(hoisterUsageList.value.filter((it) => it.hoisterID == hoisterID));
        WireropeTypeRefs.value[idx].SetList(wireropeTypeList.value.filter((it) => it.hoisterID == hoisterID));
    });
};

/********************************************** 钢丝绳选择 **********************************************/
const isShowWireropeSelect = ref(false);
const wireropeFilter = ref<any>({});
let selectIndex = ref();

//打开钢丝绳选择
const onOpenWireropeSelect = (rowIndex) => {
    if (!isSee.value) {
        selectIndex.value = rowIndex;
        isShowWireropeSelect.value = true;
    }
};

//关闭钢丝绳选择
const onCloseWireropeSelect = (selectData) => {
    isShowWireropeSelect.value = false;
    if (!Gx.IsEmpty(selectData)) {
        thisData.value.billDetailModels[selectIndex.value].guiGe = selectData.guiGe;
        thisData.value.billDetailModels[selectIndex.value].cnt = selectData.cnt;
        thisData.value.billDetailModels[selectIndex.value].diameter = selectData.diameter;
        // thisData.value.billDetailModels[selectIndex.value].remark = selectData.remark;
    }
};

//关闭
const onClose = () => {
    emits("close", false);
};

//向上抛出的事件与方法
const emits = defineEmits(["close"]);
defineExpose({ Init });
</script>

<style lang="scss">
.rowWarp {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.btnBox {
    display: flex;
    align-items: center;
}
</style>
